package com.huang.core.widget.recyclerview.layoutmanager

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MultiGridLayoutManager : GridLayoutManager {
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {}
    constructor(context: Context?, spanCount: Int) : super(context, spanCount) {}
    constructor(context: Context?, spanCount: Int, orientation: Int, reverseLayout: Boolean) : super(context, spanCount, orientation, reverseLayout) {}

    private val heightMap: MutableMap<Int, Int?> = HashMap()

    override fun onLayoutCompleted(state: RecyclerView.State?) {
        super.onLayoutCompleted(state)
        val count = childCount
        for (i in 0 until count) {
            val view = getChildAt(i)
            heightMap[i] = view?.height
        }
    }

    override fun computeVerticalScrollOffset(state: RecyclerView.State): Int {
        return if (childCount == 0) {
            0
        } else try {
            val firstVisiblePosition = findFirstVisibleItemPosition()
            val firstVisibleView = findViewByPosition(firstVisiblePosition)!!
            var offsetY = (-firstVisibleView.y).toInt()
            for (i in 0 until firstVisiblePosition) {
                offsetY += (if (heightMap[i] == null) 0 else heightMap[i])!!
            }
            offsetY
        } catch (e: Exception) {
            0
        }
    }

    /** 计算垂直滚动时滚动的距离  */
    fun computeVerticalHeight(): Int {
        return computeVerticalScrollOffset(RecyclerView.State())
    }
}